import { cloneDeep, omit } from 'lodash-es'
import type { Ref } from 'vue'

import type {
  CascaderModel,
  CascaderNodeModel,
  CascaderRegionModel,
  Data,
  NodeLevel
} from '../index'
import { useCascaderStore } from './useCascaderStore'

export type BuildDataReturn = {
  dataSource: Ref<CascaderRegionModel>
  sourceData: Ref<CascaderRegionModel>
  doLayout: () => void
}

export const useBuildData = (data: Ref<CascaderModel>) => {
  const sourceData = ref<CascaderModel>()
  const dataSource = ref<CascaderModel>()

  function buildNodes(
    nodes: CascaderNodeModel[],
    level: NodeLevel,
    region: string
  ) {
    const { nodesMap } = useCascaderStore()
    const resNodes = cloneDeep(nodes)
    resNodes.forEach((node, index) => {
      node.source = {
        // 原始索引
        index,
        // 原始区域
        region,
        // 原始层级
        level
      }
      nodesMap.value[node.node_id] = node
    })
    return resNodes
  }

  function buildData() {
    if (!data) return

    const { regionsMap, resetDiff } = useCascaderStore()
    resetDiff()

    const cascaderData: CascaderModel = cloneDeep(data.value)

    cascaderData.charts.forEach((item) => {
      buildNodes(item.node_L1, 1, item.region_id)
      buildNodes(item.node_L2, 2, item.region_id)
    })

    regionsMap.value = cascaderData.charts.reduce((acc, item) => {
      acc[item.region_id] = omit(item, ['__node_L1', '__node_L2'])
      return acc
    }, {} as Data)
    dataSource.value = cascaderData
    sourceData.value = cloneDeep(cascaderData)
  }

  watchPostEffect(() => {
    if (!data) {
      return
    }
    buildData()
  })

  return { sourceData, dataSource, doLayout: buildData }
}
